interface IListener {
    preCondition(e: EventType): boolean; // 筛选掉监听者不愿意处理的特殊类型
    notify(caster: Broadcaster, event: EventType): void;
}
export enum DataChange {
    FinishLoad, // 完成页面资源加载
    CheckTable, // 换桌
    PlayerChange,
    GameStart,
    ChangeStatus,
    OutCard,
    Double,
    MySelfOutCard, // 自己出牌
    GameOver,
    Restart
}

export interface EventType {
    action: DataChange;
    data: any
}

export class Listener implements IListener {
    preCondition(e: EventType) {
        // 不同类不同实现
        return true
    }
    notify(caster: Broadcaster, event: EventType) { }
    addListener(caster: Broadcaster) {
        caster.addListener(this)
    }
    endListener(caster: Broadcaster) {
        caster.removeListener(this)
    }
    haveListener(caster: Broadcaster): boolean {
        return caster.haveListener(this)
    }
}

export class Broadcaster {
    listeners: Set<IListener> = new Set();

    addListener(listener: IListener) {
        if (!this.listeners.has(listener)) {
            this.listeners.add(listener)
        }
    }

    removeListener(listener: IListener) {
        if (listener) {
            this.listeners.delete(listener)
        }
    }

    haveListener(listener: IListener): boolean {
        return this.listeners.has(listener)
    }

    broadcaster(e: EventType) {
        if (!e) return;
        for (const listener of this.listeners) {
            if (listener.preCondition && listener.preCondition(e)) {
                listener.notify(this, e)
            }
        }
    }
}